package com.anrongtec.zcpt.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：liuhui on 2017/2/14 15:11
 * 邮箱：liu594545591@126.com
 * 描述：ViewPagerToGallery
 */

public class ViewPagerToGallery {
    private Context context;
    private List<String> imageUrls;
    private ViewPager viewPager;
    private static ViewPagerToGallery mInstance;

    private ViewPagerToGallery() {
    }

    public static synchronized ViewPagerToGallery getInstance() {
        if (mInstance == null) {
            mInstance = new ViewPagerToGallery();
        }
        return mInstance;
    }

    /**
     * 设置数据源
     *
     * @param context
     *            context Not Null
     * @param viewPager
     *            显示数据的ViewPager Not Null
     * @param imageUrls
     *            数据源
     */
    public void setImageUrls(Context context, ViewPager viewPager, List<String> imageUrls) {
        if (this.imageUrls == null) {
            this.imageUrls = new ArrayList<>();
        }

        if (context == null || viewPager == null) {
            // 二者有一个为空时候就直接返回
            return;
        }

        if (this.context == null || this.context != context) {
            // 当context为空，代表第一次，需要赋值
            // 当当前context与参数context不同，意味着重新打开了新的页面
            this.context = context;
            this.imageUrls.clear();
            this.viewPager = viewPager;
            // 当imageUrls大小为0时候说明当前页面第一次加载，
            // 初始化ViewPager，设置大小为2/3、缓存数目、PagerAdapter
            setViewPagerSize();
            setViewPager();
        }

        if (imageUrls != null) {
            this.imageUrls.addAll(imageUrls);
        }
        // 更新数据
        this.viewPager.getAdapter().notifyDataSetChanged();
    }

    // 改变ViewPager大小，保证缓存的左右界面可以显示
    private void setViewPagerSize() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 当宽度<=0时候，说明当前界面没有初始化完成，无法计算大小
                while (viewPager.getWidth() <= 0) {
                    try {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                viewPager.setVisibility(View.INVISIBLE);
                            }
                        });
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setVisibility(View.VISIBLE);
                        // 设置ViewPager为原大小2/3，保证两边缓存的出现
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                                viewPager.getMeasuredWidth() / 3 * 2, viewPager.getMeasuredHeight());
                        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
                        viewPager.setLayoutParams(params);
                    }
                });
            }
        }).start();
    }

    private void setViewPager() {
        // 设置adapter
        viewPager.setAdapter(new MyPagerAdapter());
        // 设置缓存
        viewPager.setOffscreenPageLimit(4);
        // 设置切换动画
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageUrls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            // 确保notifyDataSetChanged()方法生效
            return POSITION_NONE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 初始化界面
            ImageView imageView = new ImageView(context);

            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            // 加载图片
            Glide.with(context).load(imageUrls.get(position)).into(imageView);

            container.addView(imageView);

            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) ((ImageView) object).getDrawable();
            // 如果图片还未回收，先强制回收该图片
            if (bitmapDrawable.getBitmap().isRecycled()) {
                bitmapDrawable.getBitmap().recycle();
            }
            container.removeView((ImageView) object);
        }
    }

    private class ZoomOutPageTransformer implements ViewPager.PageTransformer {

        private static final float MIN_SCALE = 0.9f;
        private static final float MIN_ALPHA = 0.5f;

        private float defaultScale = 0.9f;

        public void transformPage(View view, float position) {
            // 计算大小
            int pageWidth = view.getWidth();

            int pageHeight = view.getHeight();
            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);
                view.setScaleX(defaultScale);
                view.setScaleY(defaultScale);
            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as
                // well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    view.setTranslationX(horzMargin - vertMargin / 2);
                } else {
                    view.setTranslationX(-horzMargin + vertMargin / 2);
                }

                // Scale the page down (between MIN_SCALE and 1)
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

                // Fade the page relative to its size.
                view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA));

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
                view.setScaleX(defaultScale);
                view.setScaleY(defaultScale);
            }
        }

    }
}

